<?php
/**
 * 定制UpdAgentServer
 *
 * @author		黑冰 <954650386@qq.com>
 */

use \waf\Waf;
use \waf\log\WLog;
use \waf\server\UdpServer;
use \waf\modules\WCFunc;

class UdpAgentServer extends UdpServer
{
    public function onWorkerStart($objSServer, $workerId)
    {
        WLog::logSystem("onWorkerStart", __FILE__, __LINE__, __FUNCTION__);
        parent::onWorkerStart($objSServer, $workerId);

        // 定时5分钟落地数据
        swoole_timer_tick(300000, [$this, 'saveInterfaceData'],  $workerId);  // 接口调用
        swoole_timer_tick(300000, [$this, 'saveCountData'],      $workerId);  // 次数调用
    }

    public function onWorkerStop($objSServer, $workerId)
    {
        WLog::logSystem("onWorkerStop", __FILE__, __LINE__, __FUNCTION__);
        parent::onWorkerStop($objSServer, $workerId);

        // 落地数据
        $this->saveInterfaceData();
        $this->saveCountData();
    }

    /**
     * 接口调用数据统计落地
     *
     * @param int $timer_id
     * @param int $workerId
     */
    public function saveInterfaceData($timer_id = 0, $workerId = 0)
    {
        WLog::logInfo("in. workerId = $workerId, timer_id = $timer_id", __FILE__, __LINE__, __FUNCTION__);
        WLog::logDebug("data = ".WLog::toJson(Waf::WData()->getAllData()), __FILE__, __LINE__, __FUNCTION__);

        // 从当前进程中，获取累计的数据，存储到db
        // 一级key =>['waf_interface_statistics']
        // 二级key =>['server_name|module_name|interface_name']['sct' ,'sc', 'fct', 'fc']
        // sct:suc_cost_time , sc:suc_count, fct:fail_cost_time, fc:fail_count
        $key = Waf::getConfig('key', 'waf_interface_statistics');
        $arrReportData = Waf::WData()->getData($key);
        Waf::WData()->delData($key);

        if($arrReportData && is_array($arrReportData))
        {
            $time_line      = ceil(time()/300)*300;
            $report_time    = date('Y-m-d H:i:s', $time_line);
            $ip             = WCFunc::getLocalIp();

            $conf = Waf::getConfig('db', 'mysql');
            WLog::logInfo("conf = ". WLog::toJson($conf), __FILE__, __LINE__, __FUNCTION__);
            $swoole_mysql = new Swoole\Coroutine\MySQL();
            $ret = $swoole_mysql->connect($conf);
            if($ret)
            {
                foreach($arrReportData as $k => $v)
                {
                    $arrT = array();
                    $arrT = explode('|', $k);
                    $server_name    = $arrT[0];
                    $module_name    = $arrT[1];
                    $interface_name = $arrT[2];
                    unset($arrT);

                    $suc_cost_time  = intval($v['sct']);
                    $suc_count      = intval($v['sc']);
                    $fail_cost_time = intval($v['fct']);
                    $fail_count     = intval($v['fc']);

                    $sql = "insert into waf_interface_call_statistics values ('', '{$report_time}', '{$server_name}', '{$module_name}', '{$interface_name}', '{$ip}', '{$suc_cost_time}', '{$suc_count}', '{$fail_cost_time}', '{$fail_count}')";
                    WLog::logInfo("sql = $sql", __FILE__, __LINE__, __FUNCTION__);

                    $res = $swoole_mysql->query($sql);
                    if($res === false)
                    {
                        WLog::logError("exec sql fail!", __FILE__, __LINE__, __FUNCTION__);
                    }
                }
            }
        }
    }

    /**
     * 次数累计调用统计落地
     *
     * @param int $timer_id
     * @param int $workerId
     */
    public function saveCountData($timer_id = 0, $workerId = 0)
    {
        WLog::logInfo("in. workerId = $workerId, timer_id = $timer_id", __FILE__, __LINE__, __FUNCTION__);
        WLog::logDebug("data = ".WLog::toJson(Waf::WData()->getAllData()), __FILE__, __LINE__, __FUNCTION__);

        // 从当前进程中，获取累计的数据，存储到db
        // 一级key =>['waf_interface_statistics']
        // 二级key =>['server_name|module_name|interface_name']['sct' ,'sc', 'fct', 'fc']
        // sct:suc_cost_time , sc:suc_count, fct:fail_cost_time, fc:fail_count
        $key = Waf::getConfig('key', 'waf_count_statistics');
        $arrReportData = Waf::WData()->getData($key);
        Waf::WData()->delData($key);

        if($arrReportData && is_array($arrReportData))
        {
            $time_line      = ceil(time()/300)*300;
            $report_time    = date('Y-m-d H:i:s', $time_line);
            $ip             = WCFunc::getLocalIp();

            $conf = Waf::getConfig('db', 'mysql');
            WLog::logInfo("conf = ". WLog::toJson($conf), __FILE__, __LINE__, __FUNCTION__);
            $swoole_mysql = new Swoole\Coroutine\MySQL();
            $ret = $swoole_mysql->connect($conf);
            if($ret)
            {
                foreach($arrReportData as $k => $v)
                {
                    $arrT = array();
                    $arrT = explode('|', $k);
                    $server_name    = $arrT[0];
                    $module_name    = $arrT[1];
                    $interface_name = $arrT[2];
                    unset($arrT);

                    $count     = intval($v);

                    $sql = "insert into waf_count_statistics values ('', '{$report_time}', '{$server_name}', '{$module_name}', '{$interface_name}', '{$ip}', '{$count}')";
                    WLog::logInfo("sql = $sql", __FILE__, __LINE__, __FUNCTION__);

                    $res = $swoole_mysql->query($sql);
                    if($res === false)
                    {
                        WLog::logError("exec sql fail!", __FILE__, __LINE__, __FUNCTION__);
                    }
                }
            }
        }
    }
}
?>